<script lang="ts">
import {defineComponent, PropType} from 'vue'
import {useUploadFile} from "@/store/modules/uploadFile";
import {ElMessage, ElMessageBox} from "element-plus";
import fileReq from "@/api/file";
import pathBrowserify from 'path-browserify'
import ShareFile from "@/views/dashboard/ShareFile.vue";
import FileInfoDialog from "@/views/dashboard/FileInfoDialog.vue";
import {FileResult} from "@/entityType/FileResult";
import {FileUtils} from "@/utils/FileUtils";
import {CancelTokenSource} from "axios";
import {lrcReq} from "@/api/lrc";
import BtnPopover from "@/views/dashboard/BtnPopover.vue";
import {SortObjType} from "@/views/dashboard/type";
import ElRadioPlus from "@/components/ElRadioPlus/index.vue";
import SelectCustomAll from "@/views/dashboard/SelectCustomAll.vue";

export default defineComponent({
  name: "FileTools",
  components: {SelectCustomAll, ElRadioPlus, BtnPopover, FileInfoDialog, ShareFile},
  props: {
    selectFileName: Array as PropType<string[]>,
    basePath:String, // 这个就是页面的路径
    getBasePath:Function,
    selectOne: Boolean,
    files: Array as PropType<FileResult[]>,
    sortObj: {
      type: Object as PropType<SortObjType>,
      default: ()=> {}
    }
  },
  emits:['funcFinished','update:selectOne','RefreshFileList'],
  data() {
    return {
      cutFileOrDirPath: [],
      cutBasePath: '',
      copyFileOrDirPath: '',
      copyBasePath: '',
      visible: false,
      downloading: false,
      cancelToken: null as CancelTokenSource,
      RefreshFileListTime: null,
    }
  },
  created() {
    this.RefreshFileListTime = setInterval(()=>{
      this.RefreshFileList()
    },3000)
  },
  beforeUnmount() {
    if(this.RefreshFileListTime) {
      clearInterval(this.RefreshFileListTime)
    }
  },
  computed:{
    selectOneSync: {
      get() {
        return this.selectOne
      },
      set(val){
        this.$emit('update:selectOne',val)
      }
    },
    cutFileOrDirDisabled() {
      if(this.cutFileOrDirPath.length>0) {
        return false
      }
      if(this.selectFileName.length>0) {
        return false
      }
      return true
    },
    copyFileOrDirDisabled() {
      if(this.copyFileOrDirPath.length>0) {
        return false
      }
      if(this.selectFileName.length>0) {
        return false
      }
      return true
    },
  },
  methods: {
    RefreshFileList() {
      this.$emit('RefreshFileList')
    },
    getSelectPath() {
      let basePath = this.getBasePath()
      return this.selectFileName.map(i=>{
        return pathBrowserify.resolve(basePath,i)
      })
    },
    uploadFileClick() {
      useUploadFile()
        .getUploadInstance
        .open(this.basePath,()=>{
          this.$emit('funcFinished')
        })
    },
    deleteFileClick() {
      ElMessageBox.confirm('是否确认删除？','Warning', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(()=>{
        let basePaths = this.getSelectPath()
        fileReq.deleteFileOrDir(basePaths).then(res=>{
          this.$emit('funcFinished')
        })
      })
    },
    cutFileOrDir() {
      let basePath = this.getBasePath();
      if (this.cutFileOrDirPath.length === 0 || basePath === this.cutBasePath) {
        this.cutBasePath = basePath
        this.cutFileOrDirPath = this.getSelectPath()
        return
      } else {
        fileReq.removeFileOrDir(this.cutFileOrDirPath, basePath).then(res => {
          this.$emit('funcFinished')
          this.cutFileOrDirPath = []
        })
      }
    },
    copyFileOrDir() {
      let basePath = this.getBasePath();
      if (this.copyFileOrDirPath.length === 0 || basePath === this.copyBasePath) {
        this.copyBasePath = this.getBasePath()
        this.copyFileOrDirPath = this.getSelectPath()
        return
      } else {
        fileReq.copyFileOrDir(this.copyFileOrDirPath, basePath).then(res => {
          this.$emit('funcFinished')
          this.copyFileOrDirPath = []
        })
      }
    },
    ShareFileClick() {
      this.$refs.ShareFileRef.open(
        this.getBasePath(),
        this.selectFileName
      )
    },
    getFileInfoClick(){
      let path = this.getSelectPath()?.[0] || this.getBasePath()
      this.$refs.FileInfoDialogRef.open(path)
    },
    creatFile(){
      ElMessageBox.confirm("新建文件","新建文件",{
        showInput: true,
        inputPlaceholder: "新建文件",
        inputValidator:(value)=>{
          if(!value){
            return '不能为空'
          }
          return true
        }
      }).then(res=>{
        const path = pathBrowserify.resolve(this.getBasePath(),res.value)
        fileReq.createFile(path).then(res=>{
          ElMessage.success(res.data as string)
          this.$emit('funcFinished')
        })
      })
    },
    creatDir(){
      ElMessageBox.confirm("新建文件夹","新建文件夹",{
        showInput: true,
        inputPlaceholder: "新建文件夹",
        inputValidator:(value)=>{
          if(!value){
            return '不能为空'
          }
          return true
        }
      }).then(res=>{
        const path = pathBrowserify.resolve(this.getBasePath(),res.value)
        fileReq.createDir(path).then(res=>{
          ElMessage.success(res.data as string)
          this.$emit('funcFinished')
        })
      })
    },
    renameClick() {
      ElMessageBox.confirm("请输入新的名字，记得带扩展名","重命名",{
        showInput: true,
        inputPlaceholder: "重命名",
        inputValue: this.selectFileName[0],
        inputValidator:(value)=>{
          if(!value){
            return '不能为空'
          }
          return true
        }
      }).then(res=>{
        fileReq.rename(this.getSelectPath()[0],res.value).then(res=>{
          ElMessage.success(res.data as string)
          this.$emit('funcFinished')
        })
      })
    },
    DownloadFileClick() {
      ElMessageBox.confirm("开始下载？", "下载").then(() => {
        fileReq.downloadFileOrDir(this.getBasePath(),this.getSelectPath()).then(res => {
          FileUtils.fileDownLoadFromUrl(
            fileReq.getDownloadFileOrDirById(res.data.downloadFileId),
            res.data.downloadName)
        })
      })
    },
    lrcToVideo() {
      ElMessageBox.confirm("是否合并歌词为视频？", "提示").then(() => {
        let paths = this.getSelectPath()
        if(paths.length === 0) {
          paths = [this.getBasePath()]
        }
        lrcReq.run(paths).then(res=>{
          ElMessage.success(res.data as string)
        })
      })
    },
  }
})
</script>

<template>
  <div class="fileTools2">
    <div>
      <div>文件{{files.length}}</div>
      <div>选中{{selectFileName.length}}</div>
    </div>
    <div>
      <el-button
        text
        @click.stop="$refs.SelectCustomAllRef.open()"
        type="primary"
      >自定义选中</el-button>
      <SelectCustomAll
        ref="SelectCustomAllRef"
        :files="files"
        :select-file-name="selectFileName"
        :sort-obj="sortObj"
      ></SelectCustomAll>
      <BtnPopover icon="Sort">
        <div class="sortClass">
          <div>名称过滤，不区分大小写</div>
          <el-input
            v-model="sortObj.filterName"
            clearable
          ></el-input>
        </div>
        <el-divider />
        <div class="sortClass">
          <div>排序</div>
          <ElRadioPlus
            v-model="sortObj.up"
            :options="['递增','递减'].map(i=>{return {value:i,label: i}})"
          ></ElRadioPlus>
        </div>
        <el-divider />
        <div class="sortClass">
          <div>排序</div>
          <ElRadioPlus
            v-model="sortObj.sort"
            :options="['名字'].map(i=>{return {value:i,label: i}})"
          ></ElRadioPlus>
        </div>
        <el-divider />
        <div class="sortClass">
          <div>分组依据</div>
          <ElRadioPlus
            v-model="sortObj.group"
            :options="['空','类型'].map(i=>{return {value:i,label: i}})"
          ></ElRadioPlus>
        </div>
      </BtnPopover>
      <el-button
        text
        type="success"
        icon="Share"
        @click.stop="ShareFileClick"
        :disabled="selectFileName.length === 0"
        v-if="checkAuths(['share'])"
      >
      </el-button>
      <el-button
        text
        type="primary"
        @click.stop="uploadFileClick"
        icon="UploadFilled"
        v-if="checkAuths(['upload'])"
      >
      </el-button>
      <el-button
        text
        type="primary"
        @click.stop="DownloadFileClick"
        :disabled="selectFileName.length === 0"
        icon="Download"
        :class="{'rotating2s': downloading}"
      >
      </el-button>
      <el-button
        text
        type="primary"
        @click.stop="getFileInfoClick"
        :disabled="selectFileName.length > 1"
        icon="InfoFilled"
      >
      </el-button>
      <BtnPopover icon="MoreFilled">
        <div class="fileTools">
          <el-button
            text
            type="primary"
            icon="Select"
            @click.stop="selectOneSync =!selectOneSync"
          >
            {{selectOneSync?'单选':'多选'}}
          </el-button>
          <el-button
            text
            type="success"
            icon="DocumentAdd"
            @click.stop="creatFile"
            v-if="checkAuths(['mkFile'])"
          >
            新建文件
          </el-button>
          <el-button
            text
            type="success"
            icon="FolderAdd"
            @click.stop="creatDir"
            v-if="checkAuths(['mkdir'])"
          >
            新建文件夹
          </el-button>
          <el-button
            text
            type="warning"
            icon="SetUp"
            :disabled="selectFileName.length !== 1"
            @click.stop="renameClick"
            v-if="checkAuths(['rename'])"
          >
            重命名
          </el-button>
          <el-button
            text
            type="warning"
            icon="copyDocument"
            :disabled="copyFileOrDirDisabled"
            @click.stop="copyFileOrDir"
            v-if="checkAuths(['copy'])"
          >
            复制
          </el-button>
          <el-button
            text
            icon="Scissor"
            type="warning"
            :disabled="cutFileOrDirDisabled"
            @click.stop="cutFileOrDir"
            v-if="checkAuths(['cut'])"
          >
            剪切
          </el-button>
          <el-button
            @click.stop="deleteFileClick"
            text
            icon="Delete"
            type="danger"
            :disabled="selectFileName.length === 0"
            v-if="checkAuths(['del'])"
          >
            删除
          </el-button>
          <el-button
            text
            type="primary"
            icon="Refresh"
            @click.stop="lrcToVideo"
          >
            视频歌词合并
          </el-button>
        </div>
      </BtnPopover>
    </div>
    <ShareFile
      ref="ShareFileRef"
    ></ShareFile>
    <FileInfoDialog
      ref="FileInfoDialogRef"
    ></FileInfoDialog>
  </div>
</template>

<style scoped lang="scss">
@import "./var.scss";
.fileTools{
  display: flex;
  justify-content: flex-end;
  flex-wrap: wrap;
  gap: 10px;
  ::v-deep {
    .el-button{
      padding: 0px;
      height: auto;
    }
    .el-icon {
      font-size: $FileToolsHeight;
    }
  }
}
.fileTools2{
  @extend .fileTools;
  flex-wrap: nowrap;
  gap: 0px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.sortClass{
  ::v-deep{
    .el-radio{
      width: 100%;
    }
  }
}
</style>
